/**
 * Copyright (C), 2020, 安徽贝慕信息科技有限公司
 * FileName: SimpleRequestConverter
 * Author:   Allen
 * Date:     2020/8/21 14:01
 * Description: 对象参数转换
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.bim.marvel.gateway.convert;

import com.bim.marvel.gateway.client.constant.GatewayCommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.Map;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * 〈对象参数转换〉
 *
 * @author Allen
 * @date 2020/8/21
 * @since 1.0.0
 */
@Slf4j
public class SimpleRequestConverter {
    /**
     * 解析加密的请求参数
     * @param exchange 请求信息
     * @param uri 请求地址
     * @return 解析过的参数
     */
    public static Map<String, String> parseRequest(ServerWebExchange exchange, String uri) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String method = serverHttpRequest.getMethodValue().toUpperCase();
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        String serviceId = route.getUri().getHost();
        Map<String, String> params = new HashMap<>(1);
        //获得请求入参信息
        MultiValueMap<String, String> query = serverHttpRequest.getQueryParams();
        query.forEach((k, v) -> {
            params.put(k, v.get(0));
        });
        // 获取http method参数
        params.put(GatewayCommonConstants.REQUEST_HTTP_METHOD_PARAMETER_NAME, method);
        // 获得请求资源服务ID
        params.put(GatewayCommonConstants.REQUEST_SERVICE_ID, serviceId);
        // 获取URL路径
        params.put(GatewayCommonConstants.REQUEST_URI_PARAMETER_NAME, uri);
        return params;
    }
}
